<?php
namespace app\common\lib;

class Royal
{
    /**
     * 上传方法
     * @author 贺强
     * @time   2022/9/12 15:53
     * @param mixed  $file     要上传的文件流
     * @param string $folder   要上传到的文件夹
     * @param mixed  $fileType 允许上传的类型
     * @param string $filename 指定上传后的文件名称
     * @return array 返回上传结果
     */
    public static function upload($file, string $folder = '', $fileType = ['jpg', 'jpeg', 'gif', 'png'], string $filename = '')
    {
        if (empty($file)) {
            return ['code' => 100, 'message' => '请选择要上传的文件'];
        }
        if (empty($fileType)) {
            $fileType = ['jpg', 'jpeg', 'gif', 'png'];
        } elseif (is_string($fileType) && $fileType !== '*') {
            $fileType = explode(',', $fileType);
            foreach ($fileType as &$t) {
                if (substr($t, 0, 1) === '.') {
                    $t = substr($t, 1);
                }
            }
        }
        $root = root_path();
        $root = str_replace('\\', DIRECTORY_SEPARATOR, $root);
        $root = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR;
        $path = 'uploads' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR . $folder;
        if (!empty($path)) {
            $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        }
        if (!is_dir($root . $path)) {
            @mkdir($root . $path, 0755, true);
        }
        $pathinfo = pathinfo($file['name']);
        if ($fileType !== '*' && !in_array($pathinfo['extension'], $fileType)) {
            return ['code' => 101, 'message' => '文件类型不合法'];
        }
        if (empty($filename)) {
            $filename = get_microsecond() . get_random_num() . '.' . $pathinfo['extension'];
        }
        $tmp = $file['tmp_name'];
        $target = $root . $path . $filename;
        try {
            $res = move_uploaded_file($tmp, $target);
            if (!$res) {
                return ['code' => 400, 'message' => '上传失败'];
            }
            return ['code' => 200, 'message' => '上传成功', 'path' => $path . $filename];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'message' => $e->getMessage()];
        }
    }
}
